import os
import sys
import shutil
import subprocess
from pathlib import Path

def run_sphinx_apidoc():
    """运行sphinx-apidoc生成文档结构"""
    # 获取当前脚本目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    source_dir = os.path.join(script_dir, 'source')
    d5core_dir = os.path.abspath(os.path.join(script_dir, '..', 'D5Core'))
    
    # 清理旧的API文档
    for item in os.listdir(source_dir):
        item_path = os.path.join(source_dir, item)
        if item.endswith('.rst') and item not in ['index.rst', 'conf.py']:
            os.remove(item_path)
            print(f"删除文件: {item_path}")
        elif os.path.isdir(item_path) and item not in ['_static', '_templates', '_build']:
            shutil.rmtree(item_path)
            print(f"删除目录: {item_path}")
    
    # 运行sphinx-apidoc
    print("运行sphinx-apidoc生成API文档...")
    
    # 构建命令
    cmd = [
        sys.executable, '-m', 'sphinx.ext.apidoc',
        '-o', source_dir,  # 输出目录
        '-f',  # 强制覆盖现有文件
        '-e',  # 为每个模块放一个文件
        '-M',
        '-T',
        d5core_dir,  # 要处理的包路径
        os.path.join(d5core_dir, 'Details', 'D5.py')  # 排除这个模块
    ]
    
    # 执行命令
    try:
        subprocess.run(cmd, check=True, capture_output=True, text=True)
        print("sphinx-apidoc执行成功")
    except subprocess.CalledProcessError as e:
        print(f"sphinx-apidoc执行失败: {e}")
        print(f"输出: {e.stdout}")
        print(f"错误: {e.stderr}")
        return False
    
    # 移除modules.rst文件
    remove_modules_rst(source_dir)
    

    
    return True



def remove_modules_rst(source_dir):
    """删除生成的modules.rst文件"""
    modules_rst_path = os.path.join(source_dir, 'modules.rst')
    if (os.path.exists(modules_rst_path)):
        os.remove(modules_rst_path)
        print(f"删除文件: {modules_rst_path}")

def main():
    print("=" * 50)
    print("D5Core API文档生成工具")
    print("=" * 50)
    
    # 运行sphinx-apidoc
    if run_sphinx_apidoc():
        print("\n文档结构已生成! ")
    else:
        print("\n文档生成失败，请检查错误信息。")

if __name__ == "__main__":
    main()
